#include "material.h"

void CMaterialFrame::Load( std::string file )
{
	
	SDL_Surface * i = IMG_Load( file.c_str() );

	if( i == NULL )
	{
		
		Log::Debug( "Failed loading material: " + file );
		return;

		
	} else
		Log::Debug( "Successfully loaded material: " + file );
	
	int bpp = i->format->BytesPerPixel;
	int fmt = 0;

	bool bmask = false;
	
	if( i->format->Rmask != 0x000000ff )
		bmask = true;
	
	if( bpp == 4 )
	{
	
		if( bmask )
			fmt = GL_BGRA;
		else
			fmt = GL_RGBA;
		
	} else
	{
		
		if( bmask )
			fmt = GL_BGR;
		else
			fmt = GL_RGB;
		
	}
	
	glGenTextures( 1, &m_Texture );
	glBindTexture( GL_TEXTURE_2D, m_Texture );
	
	glTexImage2D( GL_TEXTURE_2D, 0, bpp, i->w, i->h, 0, fmt, GL_UNSIGNED_BYTE, i->pixels );
	
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
	
	m_FrameWidth = i->w;
	m_FrameHeight = i->h;
	
	SDL_FreeSurface( i );
	
	
}

CMaterialFrame::CMaterialFrame()
{
	

	
}

CMaterialFrame::~CMaterialFrame()
{

	glDeleteTextures( 1, &m_Texture );
	
}

CMaterial::~CMaterial()
{
	
	for( std::vector< CMaterialFrame * >::iterator iter = m_pFrames.begin();
		 iter != m_pFrames.end();)
		{
			
			CMaterialFrame * f = ( *iter );
			iter = m_pFrames.erase( iter );
			
			delete f;
	
		}
			
}

void CMaterial::AddFrame( CMaterialFrame * f )
{
	
	m_pFrames.push_back( f );
	
}

/*

void CMaterial::LoadFromFile( std::string file )
{
	
	if( file.find( ".spr" ) != std::string::npos )
	{
		
		Log::Debug( "Loading sprite set: " + file );
		
		std::ifstream fileio( file.c_str() );
		
		while( !fileio.eof() )
		{
		
			std::string idir;
			int pause, x, y;
			
			fileio >> idir >> pause >> x >> y;
			
			if( idir.length() > 4 )
			{
				
				NewFrameDataFill( idir, pause, x, y );
			
			}
				
		}
		
		fileio.close();
		
	} else
	{
	
		NewFrameDataFill( file, 0, 0.0, 0.0 );
		
	}
	
	m_Tag = file;

}*/